import * as vscode from 'vscode';

export class MyWebviewViewProvider implements vscode.WebviewViewProvider {
  public static readonly viewName = 'demoSidebar';
  private _view?: vscode.WebviewView;

  //! 暴露一个方法 用于将服务器返回的请求消息 在侧边栏中显示
  public postMessage(message: any): void {
    if (this._view) {
      this._view.webview.postMessage({
        type: 'addMessage',
        text:message,
      });
    } else {
      console.warn('Webview is not initialized.');
    }
  }

  //! 将用户输入框中的消息 发送到服务器 逻辑处理 调用 并执行 sendToLanguageServer 
  private async _sendToLanguageServer(text: string): Promise<string> {
    try {
      const response = await vscode.commands.executeCommand(
        'cw-vscode-ai.sendToLanguageServer',
        text
      );
      // 如果命令返回了结果
      if (response) {
        return response.toString();
      }
      return `正在处理消息: ${text}, 请稍后...`;
    } catch (error) {
      console.error('发送消息到语言服务器失败:', error);
      throw new Error(
        `无法连接到语言服务器: ${
          error instanceof Error ? error.message : '未知错误'
        }`
      );
    }
  }

  //! 处理接收到的聊天消息 并在聊天窗口中显示
  private _handleChatMessage(text: string) {
    if (!this._view) {
      return;
    }
    this._sendToLanguageServer(text)
      .then((response) => {
        this._view?.webview.postMessage({
          type: 'addMessage',
          text: response,
        });
      })
      .catch((error) => {
        this._view?.webview.postMessage({
          type: 'addMessage',
          text: `错误: ${error.message}`,
        });
      });
  }


  constructor(private readonly _extensionUri: vscode.Uri) {}

  public async resolveWebviewView(
    webviewView: vscode.WebviewView,
    context: vscode.WebviewViewResolveContext,
    _token: vscode.CancellationToken
  ) {
    this._view = webviewView;

    // 设置 webview 选项
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [this._extensionUri],
    };

    // 设置 webview HTML 内容
    webviewView.webview.html = this._getHtmlForWebview();

    //!监听输入框的消息 触发请求聊天接口
    webviewView.webview.onDidReceiveMessage((message) => {
      switch (message.type) {
        case 'sendMessage':
          this._handleChatMessage(message.text);
          break;
      }
    });
  }
  // 生成 webview HTML 内容
  private _getHtmlForWebview(): string {
    return `<!DOCTYPE html>
    <html lang="zh-cn">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>聊天</title>
      <style>
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          margin: 0;
          padding: 0;
          background-color: var(--vscode-editor-background);
          color: var(--vscode-editor-foreground);
        }
        .chat-container {
          display: flex;
          flex-direction: column;
          height: 100vh;
        }
        .messages-container {
          flex: 1;
          overflow-y: auto;
          padding: 10px;
          display: flex;
          flex-direction: column;
        }
        .message {
          margin-bottom: 10px;
          padding: 8px 12px;
          border-radius: 5px;
          max-width: 80%;
          word-break: break-word;
        }
        .user-message {
          background-color: var(--vscode-button-background);
          color: var(--vscode-button-foreground);
          align-self: flex-end;
        }
        .bot-message {
          background-color: var(--vscode-editor-inactiveSelectionBackground);
          color: var(--vscode-editor-foreground);
          align-self: flex-start;
        }
        .input-container {
          display: flex;
          padding: 10px;
          border-top: 1px solid var(--vscode-panel-border);
        }
        #message-input {
          flex: 1;
          padding: 8px;
          border: 1px solid var(--vscode-input-border);
          background-color: var(--vscode-input-background);
          color: var(--vscode-input-foreground);
          border-radius: 4px;
        }
        #send-button {
          margin-left: 8px;
          background-color: var(--vscode-button-background);
          color: var(--vscode-button-foreground);
          border: none;
          padding: 8px 12px;
          cursor: pointer;
          border-radius: 4px;
        }
        #send-button:hover {
          background-color: var(--vscode-button-hoverBackground);
        }
        .code-snippet {
          background-color: var(--vscode-editor-background);
          color: var(--vscode-editor-foreground);
          padding: 8px;
          border-radius: 4px;
          white-space: pre-wrap;
          word-break: break-word;
          margin: 4px 0;
        }
      </style>
    </head>
    <body>
      <div class="chat-container">
        <div id="messages" class="messages-container"></div>
        <div class="input-container">
          <input type="text" id="message-input" placeholder="输入消息..." />
          <button id="send-button">发送1111</button>
        </div>
      </div>

      <script>
        (function() {
          // 获取 VS Code API
          const vscode = acquireVsCodeApi();
          
          // 获取 DOM 元素
          const messagesContainer = document.getElementById('messages');
          const messageInput = document.getElementById('message-input');
          const sendButton = document.getElementById('send-button');
          
          // 添加消息到界面
          function addMessage(text, isUser) {
            const messageElement = document.createElement('div');
            messageElement.classList.add('message');
            messageElement.classList.add(isUser ? 'user-message' : 'bot-message');

            // 检查文本是否包含 代码片段
            const codeRegex = /\`\`\`([\s\S]*?)\`\`\`/g;
            let lastIndex = 0;
            let match;


            while ((match = codeRegex.exec(text)) !== null) {
                // 添加普通文本部分
                if (match.index > lastIndex) {
                  const textPart = text.substring(lastIndex, match.index);
                  const textNode = document.createTextNode(textPart);
                  messageElement.appendChild(textNode);
                }

                // 添加代码片段部分
                const codePart = match[1];
                console.log('codePart:111:: ', codePart);
                const codeElement = document.createElement('pre');
                codeElement.classList.add('code-snippet');
                codeElement.textContent = codePart;
                messageElement.appendChild(codeElement);

                lastIndex = codeRegex.lastIndex;
            }
            // 添加剩余的普通文本部分
            if (lastIndex < text.length) {
              const textPart = text.substring(lastIndex);
              const textNode = document.createTextNode(textPart);
              messageElement.appendChild(textNode);
            }

            messagesContainer.appendChild(messageElement);
            
            
            // 滚动到最新消息
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
          }
          
          // 发送消息
          function sendMessage() {
            const text = messageInput.value.trim();
            console.log('text:html发送消息:: ', text);
            if (text) {
              // 添加用户消息到界面
              addMessage(text, true);
              
              // 发送消息到扩展
              vscode.postMessage({
                type: 'sendMessage',
                text: text
              });
              
              // 清空输入框
              messageInput.value = '';
            }
          }
          
          // 监听按钮点击事件
          sendButton.addEventListener('click', sendMessage);
          
          // 监听回车键事件
          messageInput.addEventListener('keypress', event => {
            if (event.key === 'Enter') {
              sendMessage();
            }
          });
          
          // 监听扩展发送的消息
          window.addEventListener('message', event => {
            const message = event.data;
            switch (message.type) {
              case 'addMessage':
                addMessage(message.text, false);
                break;
            }
          });
          
          // 显示欢迎消息
          addMessage('欢迎来到聊天应用11111！请输入消息开始聊天1111。', false);
        })();
      </script>
    </body>
    </html>`;
  }
}
